import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // Load env file based on mode in the current directory
  const env = loadEnv(mode, '.')

  return {
    plugins: [react()],
    // base: '/', //正式服
    base: '/', //根路径部署
    resolve: {
      alias: {
        '@': '/src',
      },
    },
    assetsInclude: ['**/*.ttf', '**/*.woff', '**/*.woff2'], // 确保字体文件被正确处理
    build: {
      // 确保每次构建都有新的哈希，防止缓存问题
      rollupOptions: {
        output: {
          // JS文件添加时间戳确保唯一性
          entryFileNames: `assets/[name]-[hash]-${Date.now()}.js`,
          chunkFileNames: `assets/[name]-[hash]-${Date.now()}.js`,
          // CSS和其他资源文件
          assetFileNames: (assetInfo) => {
            if (assetInfo.name?.endsWith('.css')) {
              return `assets/[name]-[hash]-${Date.now()}.css`
            }
            return `assets/[name]-[hash]-${Date.now()}.[ext]`
          }
        }
      },
      // 禁用CSS代码分割，确保样式完整性
      cssCodeSplit: false,
      // 设置chunk大小警告限制
      chunkSizeWarningLimit: 1000
    },
    server: {
      host: '0.0.0.0',
      port: 5173, // 默认端口，可以根据需要修改
      proxy: {
        '/api': {
          target: env.VITE_API_BASE_URL, // 使用环境变量
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
  }
})
//  